package com.wolfking.demo.nio.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class SocketClientNio {

    public static void main(String[] args) throws Exception {
        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(false);
        sc.connect(new InetSocketAddress("127.0.0.1", 8888));
        Selector selector = Selector.open();
        sc.register(selector, SelectionKey.OP_CONNECT);
        Scanner scanner = new Scanner(System.in);
        for (; ; ) {
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if (selectionKey.isConnectable()) {
                        sc.finishConnect();
                        sc.register(selector, SelectionKey.OP_WRITE);
                        System.out.println("server connect");
                        break;
                    } else if (selectionKey.isWritable()) {
                        System.out.println("please input the message");
                        String message = scanner.nextLine();
                        System.out.println("write message ：" + message);
                        writeBuffer.clear();
                        writeBuffer.put(message.getBytes());
                        writeBuffer.flip();
                        sc.write(writeBuffer);
                        sc.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        System.out.print("receive message:");
                        SocketChannel client = (SocketChannel) selectionKey.channel();
                        //将缓冲区清空以备下次读取
                        readBuffer.clear();
                        int num = client.read(readBuffer);
                        System.out.println(new String(readBuffer.array(), 0, num));
                        //注册写操作，下一次写
                        sc.register(selector, SelectionKey.OP_WRITE);
                    } else {
                        System.out.println("fdfdf");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
